<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use app\manage\model\AuthGroupNode;
use app\manage\model\AuthNode;
use buwang\base\AdminBaseController;
use app\manage\model\Admin as AdminModel;
use app\manage\model\Token;
use buwang\service\UserService;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Member;
use app\common\model\SysLog;
use app\common\model\Member as commonMember;

class Index extends AdminBaseController
{
    /**
     * 首页
     * @return \think\response\View
     */
    public function index()
    {
        return view();
    }

    /**
     * 控制台
     * @return \think\response\View
     */
    public function dashboard()
    {
        $system_info['php_uname'] = php_uname();//系统类型及型号
        $system_info['accept_language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];//服务器语言
        $system_info['php_sapi_name'] = php_sapi_name();//获取PHP运行方式
        $system_info['php_version'] = PHP_VERSION;//获取PHP运行版本
        $system_info['zend_version'] = Zend_Version();//获取Zend版本
        $system_info['php_include_path'] = DEFAULT_INCLUDE_PATH;//获取PHP安装路径：
        $system_info['server_name'] = GetHostByName($_SERVER['SERVER_NAME']);//获取服务器IP：
//        $system_info['cpu_num'] =  $_SERVER['PROCESSOR_IDENTIFIER'];//  获取服务器CPU数量：
//        $system_info['system_root'] = $_SERVER['SystemRoot'];// 获取服务器系统目录
        $system_info['system_port'] = $_SERVER['SERVER_PORT'];//  获取服务器Web端口：：
        $system_info['system_host'] = $_SERVER["HTTP_HOST"];//  获取服务器域名：
        $system_info['max_memory'] = get_cfg_var("memory_limit") ? get_cfg_var("memory_limit") : "无";

        //上方统计角标
        $member_total = commonMember::addMemberTotal();
        $user_total = commonMember::allUserTotal();
        $recharge_total = commonMember::memberRechargeTotal();
        $app_total = commonMember::memberAppTotal();


        return view('', ['system_info' => $system_info, 'data' => compact('member_total', 'user_total', 'recharge_total', 'app_total')]);
    }

    /**
     * 菜单
     * @return \think\response\Json
     */
    public function menu()
    {
        $admin = $this->user;
        //TODO :得到登录管理员id
        $adminId = $admin['id'];  //id=1为超级管理员，拥有全部权限
        $logoImage = '/layui/images/logo.png';
        if (isset($admin['avatar']) && $admin['avatar']) $logoImage = $admin['avatar'];

        $homeInfo = [
            'title' => bw_config('backstage_top_title'),
            'href' => bw_config('backstage_top_url'),
        ];
        $logoInfo = [
            'title' => $admin['nickname'],
            'image' => $logoImage,
            'href' => '/'
        ];
        $menuInfo = AdminModel::getMenuList($adminId);
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }

    /**
     * 登录
     * @return \think\response\View
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = [
                'username' => $this->request->param('username/s'),
                'password' => $this->request->param('password/s'),
                'captcha' => $this->request->param('captcha/s'),
            ];
            $this->validate($data, 'Manage.admin_login');

            //验证密码是否正确
            $admininfo = UserService::validateLogin($data['username'], $data['password']);
            $admin = $admininfo['rs'];
            if (!$admin) return $this->error($admininfo['error']);
            $rs = UserService::loginAdmin($admin, true);
            if (!$rs['rs']) return $this->error($rs['error']);
            return $this->success('登录成功', $rs['rs']);//返回token expires_time
        }
        if ($this->isUserLogin) return $this->redirect('manage/admin/index');
        $this->layout && $this->app->view->engine()->layout($this->layout);
        return view();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $admin = $this->user;
        $scopes = $this->scopes;
        if ($scopes != 'admin') return $this->error('scopes获取错误');
        if ($this->request->isPost()) {
            if (!$this->token) return $this->error('已退出登录，勿重复点击');

            $res = Token::deleteRedisToken($this->token, $admin['id'], $scopes);
            if (!$res) {
                return $this->error(Token::getError('操作失败'));
            } else {
                return $this->success('退出成功');
            }
        }
    }


    /**
     * 管理员基本资料
     */
    public function userSetting()
    {

        $topAdminId = config('auth.super_admin_id');//超级管理员id
        $admin = $this->user;


        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdminModel::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(AdminModel::getError());
            }

        }
        $id = $admin['id'];
        $data = AuthGroupAccess::getFind($id);
        if ($topAdminId == $id) $is_super = true; else $is_super = false;
        $list = AdminModel::select()->toArray();
        //ar_dump($data);die;
        return view('user_setting', ['data' => $data, 'list' => $list, 'is_super' => $is_super]);


    }

    /**
     * 管理员修改密码
     */
    public function userPassword()
    {
        $topAdminId = config('auth.super_admin_id');//超级管理员id
        $admin = $this->user;


        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdminModel::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(AdminModel::getError());
            }

        }
        $id = $admin['id'];
        $data = AuthGroupAccess::getFind($id);
        if ($topAdminId == $id) $is_super = true; else $is_super = false;
        $list = AdminModel::select()->toArray();
        //ar_dump($data);die;
        return view('user_password', ['data' => $data, 'list' => $list, 'is_super' => $is_super]);

    }

    /**
     * 得到登录日志
     */
    public function getAdminLoginInfo()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $res = SysLog::getAdminLoginInfo($this->user->id, $page, $limit);
        return $this->success('操作成功', $res);
    }
}
